AddCSLuaFile( "cl_init.lua" )
AddCSLuaFile( "shared.lua" )

include('shared.lua')
local Ground = 1 + 0 + 2 + 8 + 32
local rel = "vehicles/tank_readyfire1.wav"
util.PrecacheSound(rel)

function ENT:Initialize()
	self.Entity:SetModel(  "models/props_lab/tpplugholder_single.mdl" )
	self.Entity:PhysicsInit( SOLID_VPHYSICS )
	self.Entity:SetMoveType(  MOVETYPE_VPHYSICS   )
	self.Entity:SetSolid( SOLID_VPHYSICS )
	self.Entity:SetName("Small.Ion.Cannon.5x5s")
	local phys = self.Entity:GetPhysicsObject()
	if (phys:IsValid()) then
		phys:Wake()
	end
	self.nextfire = CurTime()
	self.fire = false
	table.insert(servertable["ship"]["weapons"],self.Entity)
	self.targetpos = Vector(0,0,0)
end

function ENT:SpawnFunction( ply, tr )
	if ( !tr.Hit ) then return end
	local SpawnPos = tr.HitPos + tr.HitNormal * 36
	local ent = ents.Create( "Fighter_Ion_Cannon" )
	ent:SetPos( SpawnPos )
	ent:Spawn()
	ent:Activate()
	return ent
end

function ENT:Think()
	self.Entity:NextThink( CurTime() + 0.25 )
	if self.core then
		if  (self.core:IsValid()) then
			if (self.nextfire < CurTime()) then
				if self.use then self.core.turrets = self.core.turrets - 1 self.use = false end
				if self.fire then
					if (self.core.turrets < self.core.maxturrets) then
						if (self.core.capaciator > 10)then
							if (self.core.heat < 90) then
								if Fieldoffire(self.Entity,40) then
									self.core.heat = self.core.heat + 10
									self.core.capaciator = self.core.capaciator - 10
									self.core.turrets = self.core.turrets + 1
									if self.targetent:IsValid() then
										self.targetent:TakeDamage( 500, "World")
									end
									self.Entity.fire = false
									self.nextfire = CurTime() + 0.5
									self.use = true
								end
							end
						end
					end
				end
			end				
		else
			self.core = nil
		end					
	else
		self.core = getshipcore(self.Entity)
		if not self.core then
			self.Entity:NextThink( CurTime() + 5 )
			return true
		end
	end
	if self.use then
		self:EmitSound(rel,250,math.random(60,90))
		local effectdata = EffectData() 
		effectdata:SetStart(self.Entity:GetPos()) 
		effectdata:SetOrigin(self.target) 
		effectdata:SetScale( 200 ) 
		effectdata:SetMagnitude(39)
		effectdata:SetEntity(self.Entity)
		util.Effect( "ClanSmallPulseBeam", effectdata,true,true )
		self.Entity:NextThink(CurTime() + 0.05)
	end
	return true
end

function ENT:OnTakeDamage(info)
	Shieldhit(info,self.Entity)
end